package com.hyou.sc.eureka.client.auth.module.user;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.hyou.sc.eureka.client.auth.dto.form.UserForm;
import com.hyou.sc.eureka.client.auth.dto.pojo.UserDO;
import com.hyou.sc.eureka.client.auth.service.base.itfc.UserService;
import com.hyou.springboot.annotation.FormValidator;
import com.hyou.springboot.base.ResponseMessage;
import com.hyou.springboot.util.BeanCopyUtil;
import com.hyou.springboot.util.ResponseMessageUtil;
import com.hyou.springboot.validator.group.UpdateGroup;

@RestController("userUpdateController")
public class UserUpdateController {
    
    private static final Logger log = LoggerFactory.getLogger(UserUpdateController.class);
    
    @Resource(name = "userService")
    private UserService userService;
    
    @FormValidator(UpdateGroup.class)
    @PostMapping(path = "/user/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseMessage<Serializable> update(@RequestBody UserForm form) {
        log.debug("param : form : {}", form);
        
        UserDO oldUser = userService.getByPrimaryKey(Long.valueOf(form.getId()));
        
        if (null == oldUser) {
            return ResponseMessageUtil.genFailResult("用户不存在");
        }
        
        UserDO userDO = new UserDO();
        BeanCopyUtil.copyFormObject(form, userDO);
        
        userDO.setAccount(null);
        
        if (StringUtils.isNotBlank(form.getPasswd())) {
            String accountToSign = oldUser.getAccount() + form.getPasswd();
            String md5Pwd = DigestUtils.md5DigestAsHex(accountToSign.getBytes(StandardCharsets.UTF_8));
            userDO.setPasswd(md5Pwd);
        }
        
        userService.updateByPrimaryKeySelective(userDO);
        
        return ResponseMessageUtil.genSuccessResult();
    }
}
